<?php
class InvitationController extends Zend_Controller_Action
{

	private $invitation;
	private $invitationList;
	private $invitationResponse;
	private $authorizationMap;
	private $message;
	private $invitationMessage;
	private $user;
	private $theme;
	private $category;
	private $userRelation;
			
	/*********************************************************************
	 *  PRIVATE FUNCTIONS
	 *********************************************************************/

    /**
     * Post invitation comment, log user activity and send invitation owner
     * a email.
     * 
     * @param $user_id user that post the message
     * @param $comment message
     * @param $invitation_id invitation id
     */
    private function viewpostmessage($user_id, $comment, $invitation_id){
    	$db = Zend_Registry::get('db');
    	$data = array(
    		'user_id'=>$user_id,
    		'message'=>$comment,
    		'created'=>$this->_helper->generator->generateCurrentTime()
    	);
    	$db->beginTransaction();
    	$message_id = $this->message->postMessage($data);
    	$data = array(
    		'invitation_id'=>$invitation_id,
    		'message_id'=>$message_id
    	);
    	$invitationMessageId = $this->invitationMessage->addEntry($data);
    	Activity::logActivity(Activity::INVITATION_COMMENT, $user_id, $invitationMessageId, $this->_helper->generator->generateCurrentTime());
    	// send activity email
    	$invitation = Invitation::findById($invitation_id);
    	$data = array(
    		EmailMessageTemplate::TAG_SEND_USER => $this->_helper->user->getUserPresentName(User::findById($user_id)),
    		EmailMessageTemplate::TAG_INVITATION_TITLE => $invitation->title,
    		EmailMessageTemplate::TAG_MESSAGE => $comment
    	);
    	MailQueue::addToQueue(Activity::INVITATION_COMMENT, 
    							'您的朋友在你的邀请上留言', 
    							Invitation::getUser($invitation)->email, 
    							EmailMessageTemplate::getMessage(Activity::INVITATION_COMMENT, $data), 
    							$this->_helper->generator->generateCurrentTime()
    	);
    	//$this->_helper->email->sendActivityEmail(Activity::INVITATION_COMMENT, Invitation::getUser($invitation)->email, '邀请卡', $data);
    	$db->commit();
    }

    
	/*********************************************************************
	 *  COMMON ACTIONS
	 *********************************************************************/	 	
    	
    public function init()
    {
        /* Initialize action controller here */
    	$this->invitation = new Invitation();
    	$this->invitationList = new InvitationList();
    	$this->invitationResponse = new InvitationResponse();
    	$this->authorizationMap = new AuthorizationMap();
    	$this->message = new Message();
    	$this->invitationMessage = new InvitationMessage();
    	$this->user = new User();
    	$this->theme = new Theme();
    	$this->category = new Category();
    	$this->userRelation = new UserRelation();
    }

    public function indexAction()
    {
        $storage = new Zend_Auth_Storage_Session();
		$data = $storage->read();
		if(!$data){
			$this->_redirect('user/login');
		}
		$this->view->username = $data->username;
		$this->view->email = $data->email;
    }
    
    /**
     * Eidt user invitation list action.
     */
    public function edituserlistAction() {
    	$storage = new Zend_Auth_Storage_Session();
		$data = $storage->read();
		if(!$data){
			$this->_redirect('user/login');
		} else {
			$id = $this->_request->getParam('id');
			$invitation = $this->invitation->findById($id);
			$this->view->invitation = $invitation;
			$this->view->invitationUserList = $this->invitationList->findByUserId($data->id, $id);
			
			
       	    $this->view->pageTitle = "修改受邀人员列表 ".$invitation->title;
			
			$form = new AddUser();
			$this->view->form = $form;
			
		}
    }
    
    /**
     * Delete user invitation list action.
     */
    public function deleteuserlistAction() {
    	$storage = new Zend_Auth_Storage_Session();
		$data = $storage->read();
		if(!$data){
			$this->_redirect('user/login');
		} else {
			$invitation_id = $this->getRequest()->getParam("id");
			$userlist_id = $this->getRequest()->getParam("ulid");
			$this->invitationList->deleteById($userlist_id);
			$this->_redirect("invitation/edituserlist?id=".$invitation_id);
		}
    }
    
	/**
     * Edit invitation action.
     */
    public function editAction() {
    	$storage = new Zend_Auth_Storage_Session();
		$data = $storage->read();
		if(!$data){
			$this->_redirect('user/login');
		} else {
			$id = $this->_request->getParam('id');
			$invitation = Invitation::findById($id);
			$this->view->invitation = $invitation;
			
			$users = $this->invitationList->findByUserId($data->id, $id);
			
       	    $this->view->pageTitle = "修改邀请 ".$invitation->title;
			
			$form = new CreateOrEditInvitation($invitation, $users);
			$this->view->form = $form;
			
    	    $config = Zend_Registry::get('config');
			$this->view->headScript()->appendFile($config->baseurl.'/js/jquery.address-1.1.min.js');
			$this->view->headScript()->appendFile($config->baseurl.'/js/jquery.validate.min.js');
			$this->view->headScript()->appendFile($config->baseurl.'/js/createinvitation.js');
			
			if ($this->getRequest ()->isPost ()) {
				if ($form->isValid ( $_POST )) {
					$data = array(
						'id' => $form->getValue('iid'),
						'category' => $form->getValue('category'),
						'theme' => $form->getValue('theme'),
						'title' => $form->getValue('title'),
						'date' => $form->getValue('date'),
						'description' => $form->getValue('description'),
						'address' => $form->getValue('address'),
						'modified' => $this->_helper->generator->generateCurrentTime(),
						'status' => $form->getValue('status'),
						'permission_id' => $form->getValue('permission_id'),
						'open' => $form->getValue('open')
					);
					$db = Zend_Registry::get('db');
					$db->beginTransaction();
					$this->invitation->saveOrUpdateInvitation($data);
					$db->commit();
					if (!empty($this->getRequest()->SaveAndAddUser)) {
						$this->_redirect('invitation/adduserlist/iid/'.$id);
					}
				}
			}
		}
    }
    
    /**
     * Create invitation action.
     */
    public function createAction()
    {
    	$storage = new Zend_Auth_Storage_Session();
		$data = $storage->read();
		if(!$data){
			$this->_redirect('user/login');
		} else {
			
		    $this->view->pageTitle="新建活动邀请";
			$form = new CreateOrEditInvitation(null,$this->_helper->user->getUserData());
			$this->view->form = $form;
    	    $config = Zend_Registry::get('config');
			$this->view->headScript()->appendFile($config->baseurl.'/js/jquery.address-1.1.min.js');
			$this->view->headScript()->appendFile($config->baseurl.'/js/jquery.validate.min.js');
			$this->view->headScript()->appendFile($config->baseurl.'/js/createinvitation.js');
			
			
			if ($this->getRequest ()->isPost ()) {
				if ($form->isValid($_POST)) {
					$data = array(
						'user_id' => $form->getValue('user_id'),
						'category_id' => $form->getValue('category'),
			    		'theme_id' => $form->getValue('theme'),
			    		'title' => $form->getValue('title'),
			    		'date' => $form->getValue('date'),
			    		'address' => $form->getValue('address'),
			    		'description' => $form->getValue('description'),
						'created' => $this->_helper->generator->generateCurrentTime(),
						'modified' => $this->_helper->generator->generateCurrentTime()
					);
					$db = Zend_Registry::get('db');
					$db->beginTransaction();
					$invitation = $this->invitation->saveOrUpdateInvitation($data);
					Activity::logActivity(Activity::INVITATION_CREATE, $this->_helper->user->getUserData()->id, $invitation->id, $this->_helper->generator->generateCurrentTime());
					$db->commit();
					if (!empty($this->getRequest()->SaveAndAddUser)) {
						// show add invitation user form
						$this->_redirect('invitation/adduserlist/iid/'.$invitation->id);
					} else {
						$this->_redirect('invitation/createhistory');
					}
				} 
			$this->_redirect('invitation/add');
			}
		}
    }
    
    /**/
    
    public function fetchthemesbycategoryajaxAction(){
    	
		$this->_helper->viewRenderer->setNoRender();   //view info disabled
		$this->_helper->getHelper('layout')->disableLayout(); //template disabled
				
    	$category_id = $this->getRequest()->getParam('category_id');
    	
    	if(isset($category_id)){
    		$themes = Category::findThemesByCategory($category_id);
    	} else {
    		$themes = Theme::findAllAvaiableThemes(); 
    	}
        echo $this->view->invitationThemes($themes);
    }
    
    public function findthemeajaxAction(){
    	
		$this->_helper->viewRenderer->setNoRender();   //view info disabled
		$this->_helper->getHelper('layout')->disableLayout(); //template disabled
		
    	$category_id = $this->getRequest()->getParam('category_id');
		$theme_id = $this->getRequest()->getParam('theme_id');
    	
		$theme=$this->theme->findById($theme_id);
		$category = $this->category->findById($category_id);
    	
        echo $this->view->invitationTheme($theme, $category);
    }
    
    
    /**
     * Send invitation, get invitation id from form.
     * 
     * @param $createdUser user who create the invitation
     * @param $invitation_id invitation id
     */
    private function sendInvitation($createdUser, $invitation_id) {
    	$users = $this->invitationList->findByUserId($invitation_id);
    	$sendResult=array();
    	$config = Zend_Registry::get('config');
    	foreach ($users as $user) {
    		$authorizationMap = $this->authorizationMap->addAuthorization($user->id, $invitation_id, $user->email);
    		if (isset($authorizationMap)) {
    			$url = $config->baseurl."/authorization/index/key/".$authorizationMap->value;
    			$data = array(
    				EmailMessageTemplate::TAG_SEND_USER => $this->_helper->user->getUserPresentName($createdUser),
    				EmailMessageTemplate::TAG_INVITATION_URL => $url
    			);
    			MailQueue::addToQueue(
    				Activity::INVITATION_CREATE, 
    				'邀请', 
    				$user->email, 
    				EmailMessageTemplate::getMessage(Activity::INVITATION_CREATE, $data),
    				$this->_helper->generator->generateCurrentTime());
    			//$this->_helper->email->sendActivityEmail(Activity::INVITATION_CREATE, $user->email, "邀请", $data);
    		} else {
    			$sendResult[$user->email] = 2;
    		}
    	}
    	$this->view->sendResult = $sendResult;
    }
    
    /**
     * Save invitation and related send user list.
     * 
     * @param $form form element
     * @return return new created invitation object
     */
    private function saveInvitationAndUserList($form) {
    	$data = array(
    		'category' => $form->getValue('category'),
    		'theme' => $form->getValue('theme'),
    		'title' => $form->getValue('title'),
    		'date' => $form->getValue('date'),
    		'address' => $form->getValue('address'),
    		'description' => $form->getValue('description'),
    		// status - sent
    		'status' => 2,
    		'modified' => $this->_helper->generator->generateCurrentTime()
    	);    	
    	$storage = new Zend_Auth_Storage_Session();
    	$data = $storage->read();
    			
		$invitation = $this->invitation->saveOrUpdateInvitation($data);
		
		// user lists
		$user_id = $form->getValue('user_id');
		$users = $form->getValue('users');
		if (!empty($users)) {
			$this->addInvitationUserList($invitation->id, $users, 'active');
		}
		return $invitation;
    }
    
    /**
     * Add list of users to invitation list.
     * If the user already in the send list, then dont add it.
     * 
     * @param $invitation_id
     * @param $users invited user list
     * @param $status invitation list status active or pending
     */
    private function addInvitationUserList($invitation_id, $users, $status) {
    	$list = explode(",", $users);
    	$invited_user_id = -1;
    	$invitation = Invitation::findById($invitation_id);
    	$owner = Invitation::getUser($invitation);
    	foreach ($list as $email) {
    		$email = trim($email);
			$userObj = User::findByEmail($email);
			if (!$userObj) {
				$data = array(
					'username'=>'',
					'email'=>$email,
					'password'=>'',
					'status'=>'unregistered',
					'created'=>$this->_helper->generator->generateCurrentTime(),
					'registration_key'=>''
				);
				$invited_user_id = User::addUser($data);
			} else {
				$invited_user_id = $userObj->id;
			}
			$this->invitationList->addNewUserToList($invitation_id, $invited_user_id, $status);
			$data = array(
				'original_user_id'=>$owner->id,
				'potential_user_id'=>$invited_user_id,
				'relation_type'=>1,
				'alias'=>null,
				'created'=>$this->_helper->generator->generateCurrentTime()
			);
			UserRelation::addOrUpdateUserRelation($data);
    	}
    }
    
    /**
     * Delete invitaion action.
     */
    public function deleteAction() {
    	$storage = new Zend_Auth_Storage_Session();
		$data = $storage->read();
		if(!$data){
			$this->_redirect('user/login');
		} else {
			$id = $this->getRequest()->getParam('id');
			$db = Zend_Registry::get('db');
			$db->beginTransaction();
			$this->invitationList->deleteByInvitationIdAndUserId($id, $data->id);
			$this->invitation->deleteById($id);
			$db->commit();
			
			$this->_redirect("user/index");
		}
    }
    /**
     * View action, when invited people view the invitation.
     */
    public function viewAction() {
        $this->_helper->getHelper('layout')->disableLayout(); //template disabled
    	$invitation_id = $this->getRequest()->getParam('iid');
    	$invited_user_id = $this->getRequest()->getParam('uid');
    	$key = $this->getRequest()->getParam('key');
    	$invitation = $this->invitation->findById($invitation_id);
    	$invitingUser = User::findById($invitation->user_id);
    	
    	// by default, user not allowed to view the invitation.
    	$permission = $this->checkViewInvitationPermission($invitation, $invited_user_id, $key);
    	
    	// create send request for approval if logged in user
    	if ($permission == 2 || $permission == 4) {
    		
    		$approvalForm = new ApprovalForm($this->_helper->user->getUserData(), $invitation_id);
    		$this->view->approvalForm = $approvalForm;  	
    	} else if ($permission == 1) {
    		$user = User::findById($this->_helper->user->getUserData()->id);
    		$invited_user_id = $user->id;
    	} else if ($permission == 3) {
    		$user = User::findById($invited_user_id);
    	}
    	
    	// if the user in session is same as invitation's user, 
    	// then allow him to comment on it.
    	if ($invitation->user_id == $user->id) {
    		$invited_user_id = $user->id;
    	}
    	
    	$this->view->permission = $permission;
    	$this->view->invitation = $invitation;
    	$this->view->invitingUser = $invitingUser;
    	
     	$resources = Theme::getResourceByType(Invitation::getTheme($invitation), '2');
    	$this->view->themeCSS = $resources[0]->filename;
    	
    	$invitationMessageForm = new InvitationMessageForm($invited_user_id, $invitation_id, null, null);
    	$this->view->invitationMessageForm = $invitationMessageForm;

    	
    	if ($this->getRequest()->isPost()) {
    		if ($invitationMessageForm->isValid($_POST)) {
    			$comment = $invitationMessageForm->getValue('comment');
    			$user_id = $invitationMessageForm->getValue('user_id');
    			$invitation_id = $invitationMessageForm->getValue('invitation_id');
    			
    			$this->viewpostmessage($user_id, $comment, $invitation_id);
    		}
    		
    		if ($approvalForm->isValid($_POST)) {
    			$invitation_id = $approvalForm->getValue('invitation_id');
    			$user_id = $approvalForm->getValue('user_id');
    			$email = $approvalForm->getValue('email');
    			$db = Zend_Registry::get('db');
    			$db->beginTransaction();
    			if (isset($user_id)) {
    				// find user id, mean the user is already in db
    				$user = User::findById($user_id);
    				if (!isset($this->invitationList->findUnique($invitation_id, $user_id)->status)) {
	    				$id = $this->invitationList->addNewUserToList($invitation_id, $user_id, 'pending');
	    				$this->authorizationMap->addAuthorization($user_id, $invitation_id, $user->email);
	    				Activity::logActivity(Activity::ATTEND_INVITATION_REQUEST, $user_id, $id, $this->_helper->generator->generateCurrentTime());
	    				// send activity email.
	    				$invitation = Invitation::findById($invitation_id);
	    				$data = array(
	    					EmailMessageTemplate::TAG_SEND_USER => $user->email, 
	    					EmailMessageTemplate::TAG_INVITATION_TITLE => $invitation->title
	    				);
	    				MailQueue::addToQueue(
	    					Activity::ATTEND_INVITATION_REQUEST, 
	    					'申请加入邀请', 
	    					Invitation::getUser($invitation)->email, 
	    					EmailMessageTemplate::getMessage(Activity::ATTEND_INVITATION_REQUEST, $data),
	    					$this->_helper->generator->generateCurrentTime());
	    				//$this->_helper->email->sendActivityEmail(Activity::ATTEND_INVITATION_REQUEST, Invitation::getUser($invitation)->email, '邀请卡', $data);
	    				$this->view->message = 'Your request has been sent, wait for approval!';
    				} else {
    					$this->view->message = 'You have already been invited, wait for approval.';
    				}
    			} else {
    				// if user id is not found, then register the email and add to list
    				$user = $this->user->findByEmail($email);
    				if (isset($user)) {
    					$user_id = $user->id;
    				} else {
	    				$data = array(
							'username'=>'',
							'email'=>$email,
							'password'=>'',
							'status'=>'unregistered',
							'created'=>$this->_helper->generator->generateCurrentTime(),
							'registration_key'=>''
						);
	    				$user_id = $this->user->addUser($data);
    				}
    				if (!isset($this->invitationList->findUnique($invitation_id, $user_id)->status)) {
	    				$this->invitationList->addNewUserToList($invitation_id, $user_id, 'pending');
	    				$this->authorizationMap->addAuthorization($user_id, $invitation_id, $user->email);
	    				$this->view->message = 'Your request has been sent, wait for approval!';
    				} else {
    					$this->view->message = 'You have already been invited.';
    				}
    			}
    			$db->commit();
    		}
    	}
    	
    	$this->view->invitedUser= $user;
    	
    	$messages = $this->invitation->findAllComment($invitation_id);
    	$this->view->invitatioinMessageForm = $invitationMessageForm;
    	$this->view->messages = $messages;
    }
    
    /**
     * Check user view invtitation permission.
     * Permission definition:
     * 0 - not accessable
     * 1 - loggedin user and be invited
     * 2 - loggedin user but not be invited but the invitation is open, ask for approval
     * 3 - unloggedin user but given key is matched, use this key thoughout the form
     * 4 - unloggedin user and given key is not matched, prompt to quick register function
     * 5 - wrong url
     * 
     * @param $invitation invitation
     * @param $invited_user_id invited user id
     * @param $key authorization key from requst
     * @return return permission value
     */
    private function checkViewInvitationPermission($invitation, $invited_user_id, $key) {
    	$permission = 0;
    	if (isset($invitation)) {
	    	if ($this->_helper->user->isLoggedIn()) {
	    		$user = User::findById($this->_helper->user->getUserData()->id);
	    		if(User::isInvited($user, $invitation) || $invitation->user_id == $user->id) {
	    			$permission = 1 | $permission;
	    		} else {
	    			// not be invited, check if the invitation is public,
	    			// if true, then user might also be able to join
	    			// otherwise, not allowed to view invitation
	    			if ($invitation->permission_id == Invitation::PUBLIC_INVITATION
	    				|| $invitation->permission_id == Invitation::OPEN_INVITATION) {
		    			$permission = 2 | $permission;
	    			}
	    		}
	    	} else {
	    		if(isset($invited_user_id)) {
		    		// not logged in, check the key if they are matched
		    		if ($this->authorizationMap->keyMatch($invitation->id, $invited_user_id, $key)) {
		    			$permission = 3 | $permission;
		    		} else {
		    			// if invitation is public, then it might be possible to join as well
		    			if ($invitation->permission_id == 2) {
		    				$permission = 4 | $permission;
		    			}
		    		}
	    		} else {
	    			$permission = 5;
	    		}
	    	}
    	} else {
    		// wrong url.
    		$permission = 5;
    	}
    	return $permission;
    }

    
    /**
     * Statistic action.
     */
    public function statsAction() {
    	$storage = new Zend_Auth_Storage_Session();
		$data = $storage->read();
		if(!$data){
			$this->_redirect('user/login');
		} else {
			
			$invitation_id = $this->getRequest()->getParam('id');
			$invitation = $this->invitation->findById($invitation_id);
			
			if ($invitation->user_id == $data->id) {
				 $selectYes = $this->invitation->findInvitationResponse($invitation_id, $this->invitation->select()->where('response=?', 1));
				 $selectNo = $this->invitation->findInvitationResponse($invitation_id, $this->invitation->select()->where('response=?', 0));
				 $selectMaybe = $this->invitation->findInvitationResponse($invitation_id, $this->invitation->select()->where('response=?', 2));
				 // get those who haven't click the invitation link
				 $notEchoUsers = $this->invitation->findInvitationSendOutStatus($invitation_id, 0);
				 
				 $this->invitation = $invitation;
				 $this->view->selectYes = $selectYes;
				 $this->view->selectNo = $selectNo;
				 $this->view->selectMaybe = $selectMaybe;
				 $this->view->notEchoUsers = $notEchoUsers;
				 $this->view->pageTitle=$invitation->title."的数据统计";
			} else {
				echo "Not allow to view stats";
				exit;
			}
		}
    }
    
    
    public function createhistoryAction() {
        $storage = new Zend_Auth_Storage_Session();
		$data = $storage->read();
		if(!$data){
			$this->_redirect('user/login');
		} else {
			$invitation = new Invitation();
			$invitations = $invitation->findInvitationByUser($data->id);
			
			$this->view->paginator = $this->_helper->paginator($this->_getParam('page', 1), $invitations);
			$this->view->pageTitle=$this->_helper->user->getUserData()->username."建立的邀请";
		
			
    	    $config = Zend_Registry::get('config');
			$this->view->headScript()->appendFile($config->baseurl.'/js/InvitationList.js');
		}
		
    }
    
    
    private function deletecomment($invitation_id,$message_id) {
        $db = Zend_Registry::get('db');
    	$db->beginTransaction();
    	$this->invitationMessage->deleteByInvitationAndMessageId($invitation_id, $message_id);
    	$this->message->deleteById($message_id);
    	$db->commit();
    }
    /**
     * Delete user comment action.
     * Only be able to delete comment which
     * 1. invitation creator
     * 2. comment creator
     */
    public function deletecommentAction() {
    	$invitation_id = $this->getRequest()->getParam('iid');
    	$user_id = $this->getRequest()->getParam('uid');
    	$message_id = $this->getRequest()->getParam('mid');
    	
    	$this->deletecomment($invitation_id,$message_id);
    	$this->_redirect('invitation/view/iid/'.$invitation_id.'/uid/'.$user_id);
    }
    
    public function viewdeletecommentajaxAction() {
    	   
		$this->_helper->viewRenderer->setNoRender();   //view info disabled
		$this->_helper->getHelper('layout')->disableLayout(); //template disabled
		
		$invited_user_id = $this->getRequest()->getParam('invited_user_id'); 
		$message_id = $this->getRequest()->getParam('message_id'); 
    	$invitation_id = $this->getRequest()->getParam('invitation_id');
    	
	    $user_data = $this->view->loggedInUser();
    	
    	$this->deletecomment($invitation_id,$message_id);
    	
    	echo $this->view->invitationComment($invited_user_id,$invitation_id,$user_data);
    }
    
    /**
     * Process action that those waiting for approval invitation request.
     */
    public function invitationlistAction() {
    	$invitation_id = $this->getRequest()->getParam('id');
    	$invitation = Invitation::findById($invitation_id);
    	$invitedUsers = Invitation::getInvitedUsers($invitation);
    	$this->view->invitedUsers = $invitedUsers;
    	$this->view->invitation = $invitation;
    }
    
    /**
     * modify invitation list, approve or delete.
     */
    public function invitationlistmodifyAction() {
    	$do = $this->getRequest()->getParam('do');
    	$invitation_id = $this->getRequest()->getParam('id');
    	$invited_user_id = $this->getRequest()->getParam('uid');
    	$db = Zend_Registry::get('db');
    	$db->beginTransaction();
    	if ($do == 'delete') {
    		$this->authorizationMap->deleteByInvitationAndUserId($invitation_id, $invited_user_id);
    		$this->invitationList->deleteByInvitationIdAndUserId($invitation_id, $invited_user_id);
    	} else if ($do == 'approve') {
    		$this->invitationList->approveInvitation($invitation_id, $invited_user_id);
    	}
    	$db->commit();
    	$url = $this->view->url(array('controller'=>'invitation', 'action'=>'invitationlist', 'id'=>$invitation_id));
    	$this->_redirect('/invitation/');
    }
    
    /**
     * Add user to given invitation, and send invitation directly if necessary.
     */
    public function adduserlistAction() {
    	if ($this->_helper->user->isLoggedIn()) {
	    	$this->view->pageTitle="添加你要邀请的人";
	    	$config = Zend_Registry::get('config');
			$this->view->headScript()->appendFile($config->baseurl.'/js/jquery.validate.min.js');
			$this->view->headScript()->appendFile($config->baseurl.'/js/adduserlist.js');
				
	    	$invitation_id = $this->getRequest()->getParam('iid');
	    	$users = $this->invitationList->findByUserId($invitation_id);
	    	$invitationUserForm = new AddInvitationUserList($invitation_id, $users);
	    	$this->view->form = $invitationUserForm;
	    	$this->view->invitation = Invitation::findById($invitation_id);
	    	$this->view->theme = Invitation::getTheme($this->view->invitation);
			$this->view->category = Invitation::getCategory($this->view->invitation);
	    	$css = Theme::getResourceByType($this->view->theme,'2');   	
			$this->view->headLink()->appendStylesheet($config->baseurl.'/res/css/'.$css[0]->filename);
	    	
	    	if ($this->getRequest ()->isPost ()) {
				if ($invitationUserForm->isValid($_POST)) {
					$invitation_id = $invitationUserForm->getValue('iid');
					$invitation = Invitation::findById($invitation_id);
					$users = $invitationUserForm->getValue('users');
					if (!empty($users)) {
						$db = Zend_Registry::get('db');
						$db->beginTransaction();
						$data = array(
							'id' => $invitation_id,
							'status' => 1,
							'modified' => $this->_helper->generator->generateCurrentTime()
						);
						// update invitation status
						$this->invitation->saveOrUpdateInvitation($data);
						// add inivtation user list
						$this->addInvitationUserList($invitation_id, $users, 'active');
						if (!empty($this->getRequest()->SaveAndSend)) {
							$this->sendInvitation(Invitation::getUser($invitation), $invitation_id);
						}
						$db->commit();
					}
					$this->_redirect('invitation/createhistory');
	    		}
	    	}
    	} else {
    		$this->_redirect('user/login');
    	}
    }
    
    
	/**
	 * Grant attend invitation request.
	 * Need check if the user is login.
	 */
	public function grantattendrequestAction() {
		if ($this->_helper->user->isLoggedIn()) {
			$invitation_id = $this->_getParam('iid');
			$user = User::findById($this->_helper->user->getUserData()->id);
			$invitation = Invitation::findById($invitation_id);
			$this->view->attendUsers = User::getUserAttendRequestByStatus($invitation, 'pending');
			$this->view->invitation = $invitation;
			
			// if uid is given then grant this user to attend the invitation.
			$attend_user_id = $this->_getParam('uid');
			if (isset($attend_user_id)) {
				$config = Zend_Registry::get('config');
				$invitedUser = User::findById($attend_user_id);
				$invitationList = $this->invitationList->findUnique($invitation_id, $attend_user_id);
				// only need to do this when the user is not invited.
				if (isset($invitationList) && $invitationList->status != InvitationList::ACTIVE) {
					$db = Zend_Registry::get('db');
					$db->beginTransaction();
					$this->invitationList->approveInvitation($invitation_id, $attend_user_id);
					// send out email with new invitation link
					$authorizationMap = $this->authorizationMap->findByUnique($invitation_id, $attend_user_id);
					// add activity log
					Activity::logActivity(Activity::APPROVE_ATTEND_REQUEST, $invitation->user_id, $invitationList->id, $this->_helper->generator->generateCurrentTime());
					// send activity email, (approve attend request)
					$data = array(
						EmailMessageTemplate::TAG_SEND_USER => $this->_helper->user->getUserPresentName($user),
						EmailMessageTemplate::TAG_INVITATION_TITLE => $invitation->title
					);
					MailQueue::addToQueue(
						Activity::APPROVE_ATTEND_REQUEST, 
						'接受你的加入邀请请求', 
						$invitedUser->email, 
						EmailMessageTemplate::getMessage(Activity::APPROVE_ATTEND_REQUEST, $data), 
						$this->_helper->generator->generateCurrentTime());
					//$this->_helper->email->sendActivityEmail(Activity::APPROVE_ATTEND_REQUEST, $invitedUser->email, "邀请卡", $data);
					// send new invitation url
					if (isset($authorizationMap)) {
						$url = $config->baseurl."/authorization/index/key/".$authorizationMap->value;
						$data = array(
							EmailMessageTemplate::TAG_SEND_USER => $this->_helper->user->getUserPresentName($user),
							EmailMessageTemplate::TAG_INVITATION_URL => $url
						);
						MailQueue::addToQueue(
							Activity::INVITATION_CREATE, 
							'邀请', 
							$invitedUser->email, 
							EmailMessageTemplate::getMessage(Activity::INVITATION_CREATE, $data),
							$this->_helper->generator->generateCurrentTime());
						//$this->_helper->email->sendActivityEmail(Activity::INVITATION_CREATE, $invitedUser->email, "邀请", $data);
					}
					// add this user response to 'attend' since he request to attend to the invitation.
					$this->authorizationMap->setStatus($authorizationMap->value, AuthorizationMap::MAIL_ACCESSED);
					$db->commit();
				}
				echo 'Successful!';
			}
		} else {
			$this->_redirect('/user/login');
		}
	}
    
    public function testAction() {
//    	$invitation = $this->invitation->findById(2);
//    	$theme = Invitation::getTheme($invitation);
//    	echo $theme->name;
//    	echo "aa";
		
		
		$tr = new Zend_Mail_Transport_Smtp('mail.weimingge.com');
		Zend_Mail::setDefaultTransport($tr);
    	$email='lhj1982@gmail.com';
    	
    	$mail = new Zend_Mail ();
    	$mail->setFrom ('no-reply@weimingge.com', 'Chomp! Alerts');
    	$mail->addTo ($email, "Huajun Li");
    	$mail->setSubject ('Your feeds have been updated');
    	$mail->setBodyText ("One of your subscribed feeds, ");
    	$mail->send ($tr);
		echo 'dd';
    	exit;
    }
 	
    
	/**********************************************************************
	 *  AJAX CALLS
	 **********************************************************************/   
    
    /**
     * by passing $invitation_user_id,
     * 			   $comment
     * 			   $invitation_id 
     * to get all the messages
     * 
     * Called by view.js
     */
    public function viewmessageajaxAction(){
    	   
		$this->_helper->viewRenderer->setNoRender();   //view info disabled
		$this->_helper->getHelper('layout')->disableLayout(); //template disabled
		
		$invited_user_id = $this->getRequest()->getParam('invited_user_id'); 
		$comment = $this->getRequest()->getParam('comment'); 
    	$invitation_id = $this->getRequest()->getParam('invitation_id');
    	
    	$this->viewpostmessage($invited_user_id, $comment, $invitation_id);
    	$user_data = $this->view->loggedInUser();
    	
    	echo $this->view->invitationComment($invited_user_id, $invitation_id, $user_data);
    }
    
    public function viewattendajaxAction() {
		$this->_helper->viewRenderer->setNoRender();   //view info disabled
		$this->_helper->getHelper('layout')->disableLayout(); //template disabled
		
		$invited_user_id = $this->getRequest()->getParam('invited_user_id'); 
    	$invitation_id = $this->getRequest()->getParam('invitation_id');
    	$response = $this->getRequest()->getParam('response');
    	
    	$invitedUser = User::findById($invited_user_id);
    	$invitation = $this->invitation->findById($invitation_id);
    	
    	$db = Zend_Registry::get('db');
    	$db->beginTransaction();
    	$invitationResponse = $this->invitationResponse->addResponse($invitation_id, $invited_user_id, $response);
    	Activity::logActivity(Activity::INVITATION_REPLY, $invited_user_id, $invitationResponse, $this->_helper->generator->generateCurrentTime());
    	
    	$data = array(
    		EmailMessageTemplate::TAG_SEND_USER => $this->_helper->user->getUserPresentName($invitedUser),
    		EmailMessageTemplate::TAG_INVITATION_TITLE => $invitation->title
    	);
    	$body = EmailMessageTemplate::getMessage(Activity::INVITATION_REPLY, $data);
    	MailQueue::addToQueue(Activity::INVITATION_REPLY, "邀请", Invitation::getUser(Invitation::findById($invitation_id))->email, $body, $this->_helper->generator->generateCurrentTime());
    	$db->commit();
    	
    	echo $this->view->invitationAttend($invitation, $invitedUser);
    }
}

